/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package BLL;

import DAL.ConnectData;
import DTO.Favorite;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author mrson
 */
public class BFavorite {
    ConnectData condata;
    
    public BFavorite(){
        condata = new ConnectData();
    }
    
    public ArrayList<Favorite> getAll(String query){
        
            ArrayList<Favorite> Favorites = new ArrayList<Favorite>();
            Favorite favorite = null;
            try {
            ResultSet rs = condata.executeQuery(query);
            while(rs.next()){
                favorite = new Favorite();
                favorite.setFavoriteId(rs.getInt("favoriteId"));
                favorite.setProductId(rs.getInt("productId"));
                favorite.setUserId(rs.getInt("userId"));
                Favorites.add(favorite);
            }
            this.condata.close();
       } catch (Exception ex) {
            System.out.print(ex.toString());
        }
        return Favorites.isEmpty()?null:Favorites;
    }
    
    public ArrayList<Favorite> getAll(){
        String sql = "select * from tblFavorite";
        return this.getAll(sql);
    }
    
    public Favorite getById(int favoriteId){
        String sql = "select * from thlFavorite where favoriteId="+favoriteId;
        ArrayList<Favorite> favorites = this.getAll(sql);
        return favorites==null?null:favorites.get(0);
    }
    
    public ArrayList<Favorite> getByUserId(int userId)
    {
        String sql = "select * from tblFavorite where userId = "+userId;
        return this.getAll(sql);
    }
    
 
    
   public boolean insert(Favorite favorite){
        
            boolean check = false;
            int rs = -1;
            String sql = "insert into tblFavorite (userId, productID)" +
            		" values("+favorite.getUserId()+","+favorite.getProductId()+")";
            try {
            rs = condata.executeUpdate(sql);
            if(rs>0){
                check = true;
            }
            
        } catch (SQLException ex) {
            Logger.getLogger(BFavorite.class.getName()).log(Level.SEVERE, null, ex);
        }
        return check;
    }
   
   public boolean delete(int favoriteId)
   {
       boolean check = false;
            int rs = -1;
            String sql = "DELETE FROM tblFavorite WHERE favoriteId= "+favoriteId;
            try {
            rs = condata.executeUpdate(sql);
            if(rs>0){
                check = true;
            }
            
        } catch (SQLException ex) {
            Logger.getLogger(BFavorite.class.getName()).log(Level.SEVERE, null, ex);
        }
        return check;
   }
    
}
